//
//  YBHttpTool.m
//  Cocoachina
//
//  Created by 尚往文化 on 17/9/15.
//  Copyright © 2017年 YBing. All rights reserved.
//

#import "YBHttpTool.h"
#import "NSString+MD5Addition.h"

#ifndef kFileNameKey
#define kFileNameKey @"kFileNameKey"
#endif
#ifndef kResultKey
#define kResultKey @"kResultKey"
#endif

@implementation YBHttpTool

+ (void)get:(NSString *)url success:(void(^)(TFHpple *doc))success failure:(void (^)(NSError *error))failure
{
    [self get:url cacheType:YBCacheTypeReloadIgnoringLocalCacheData success:success failure:failure];
}

+ (void)get:(NSString *)url cacheType:(YBCacheType)cacheType success:(void(^)(TFHpple *doc))success failure:(void (^)(NSError *error))failure
{
    //缓存数据的文件名 data
    NSDictionary *dataDict = [self getCache:cacheType url:url success:success];
    NSString *fileName = dataDict[kFileNameKey];
    if ([dataDict[kResultKey] boolValue]) return;
    
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSError *error = nil;
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url] options:NSDataReadingMappedIfSafe error:&error];
        if (error) {
            if (failure) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    failure(error);
                });
            }
        } else {
            [YBCacheTool cacheForData:data fileName:fileName];
            TFHpple *doc = [[TFHpple alloc] initWithHTMLData:data];
            if (success) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    success(doc);
                });
            }
        }
    });
}

+ (NSDictionary *)getCache:(YBCacheType)cacheType url:(NSString *)url success:(void(^)(TFHpple *doc))success;
{
    //缓存数据的文件名
    NSString *fileName = url;
    NSData *data = [YBCacheTool getCacheFileName:fileName];
    
    BOOL result = NO;
    
    if (data) {
        TFHpple *doc = [[TFHpple alloc] initWithHTMLData:data];
        if (cacheType == YBCacheTypeReloadIgnoringLocalCacheData) {//忽略缓存，重新请求
            
        } else if (cacheType == YBCacheTypeReturnCacheDataDontLoad) {//有缓存就用缓存，没有缓存就不发请求，当做请求出错处理（用于离线模式）
            
        } else if (cacheType == YBCacheTypeReturnCacheDataElseLoad) {//有缓存就用缓存，没有缓存就重新请求(用于数据不变时)
            if (success) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    success(doc);
                });
            }
            result = YES;
            
        } else if (cacheType == YBCacheTypeReturnCacheDataThenLoad) {///有缓存就先返回缓存，同步请求数据
            if (success) {
                success(doc);
            }
        } else if (cacheType == YBCacheTypeReturnCacheDataExpireThenLoad) {//有缓存 判断是否过期了没有 没有就返回缓存
            //判断是否过期
            if (![YBCacheTool isExpire:fileName]) {
                if (success) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        success(doc);
                    });
                }
                result = YES;
            }
        }
    }
    return @{kFileNameKey:fileName,
             kResultKey:@(result)};
}

@end
